from xpinyin import Pinyin
from tkinter import Button, Tk, messagebox, Label, Listbox, TclError
from random import choice, shuffle
from os import listdir
from typing import List
from json import load


buttons : List[Button] = list()
datas = {}
now = stop = None

def reset_answers():
    global buttons, now, stop
    data = choice(list(datas.keys()))
    now = Label(root, text=data)
    now.pack()
    if not datas[data]["all"]:
        answers = p.get_pinyins(data, splitter=' ', tone_marks='marks')
    else:
        answers = datas[data]["all"]
    if not datas[data]["ans"]:
        answer = p.get_pinyin(data, splitter=' ', tone_marks='marks')
    else:
        answer = datas[data]["ans"]
    shuffle(answers)
    for j in answers:
        if j == answer:
            b = Button(root, text=j, command=current_click)
            buttons.append(b)
            b.pack()
        else:
            b = Button(root, text=j, command=wrong_click)
            buttons.append(b)
            b.pack()
    stop = Button(root, text="退出", command=quit)
    stop.pack()



def clear_window():
    for j in buttons:
        j.destroy()
    now.destroy()
    stop.destroy()
    reset_answers()


def current_click():
    messagebox.showinfo("答对了", "答对了")
    clear_window()


def wrong_click():
    messagebox.showerror("答错了", "答错了")


file_choice = Tk()
file_choice.title("选择文件")
Label(file_choice, text="选择符合条件的文件(*.json)").pack()
files = Listbox(file_choice, selectmode="single")
files.pack()
def get_file():
    global datas
    try:
        with open(files.get(files.curselection()), "r", encoding="utf-8") as e:
            datas = load(e)

        file_choice.destroy()
    except TclError:
        pass
Button(file_choice, text="确认", command=get_file).pack()
for i in listdir():
    if i.endswith(".json"):
        files.insert("end", i)
file_choice.mainloop()

p = Pinyin()

root = Tk()
root.title("测试")
root.geometry("800x800")
reset_answers()
root.mainloop()